package com.example.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.domain.PageResult;
import com.example.demo.domain.entity.User;
import com.example.demo.domain.entity.UserRole;
import com.example.demo.domain.exam.Paging;
import com.example.demo.domain.exam.QueryModel;
import com.example.demo.domain.exam.condition.ExamClassStaffCondition;
import com.example.demo.dto.UserListDto;
import com.example.demo.exception.ValidatorException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.UserRoleMapper;
import com.example.demo.param.UserParam;
import com.example.demo.service.UserService;
import com.example.demo.tool.IdCardUtils;
import com.example.demo.utils.RedisUtil;
import com.example.demo.utils.TokenUtils;
import com.example.demo.utils.ValidatorUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
* @author hspcadmin
* @description 针对表【user(普通用户信息)】的数据库操作Service实现
* @createDate 2024-02-20 09:28:29
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public Page<User> list(UserParam param) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();

        if (null != param.getId()){
            queryWrapper.eq("id",param.getId());
        }

        if (!StringUtils.isEmpty(param.getUsername())){
            queryWrapper.like("username",param.getUsername());
        }

        if (!StringUtils.isEmpty(param.getEmail())){
            queryWrapper.eq("email",param.getEmail());
        }

        if (!StringUtils.isEmpty(param.getPhone())){
            queryWrapper.eq("phone",param.getPhone());
        }

        if (!StringUtils.isEmpty(param.getRealName())){
            queryWrapper.eq("real_name",param.getRealName());
        }

        if (null != param.getSex()){
            queryWrapper.eq("sex",param.getSex());
        }

        if (!StringUtils.isEmpty(param.getStatus())){
            queryWrapper.eq("status",param.getStatus());
        }

        if (!StringUtils.isEmpty(param.getRole())){
            queryWrapper.eq("role",param.getRole());
        }

        if (null != param.getIsIdentity()){
            queryWrapper.eq("is_identity",param.getIsIdentity());
        }
        if (null != param.getIdentify()){
            queryWrapper.eq("identify",param.getIdentify());
        }


        Page<User> page = new Page<>(param.getCurrent(), param.getSize());

        return userMapper.selectPage(page, queryWrapper);
    }

    @Override
    public PageResult<UserListDto> listPage(QueryModel<UserParam> model) {
        UserParam condition = Optional.ofNullable(model.getCondition()).orElse(new UserParam());

        Paging paging = Optional.ofNullable(model.getPaging()).orElse(new Paging());
        paging.setPageIndex((paging.getPageIndex() - 1) * paging.getPageSize());

        List<UserListDto> userListDtos = userMapper.listPage(condition, paging);
        Long aLong = userMapper.countListPage(condition, paging);

        return PageResult.of(userListDtos).totalCount(aLong);
    }

    @Override
    public void identity(UserParam param) {
        ValidatorUtil.require(param.getIdCard(), "身份证号码");
        ValidatorUtil.require(param.getRealName(), "真实姓名");

        if (!IdCardUtils.isValidIdCard(param.getIdCard())){
            throw new ValidatorException("身份证号码输入错误");
        }

        idCardUnique(param.getIdCard());

        User user = new User();
        user.setId(param.getId());
        user.setRealName(param.getRealName());
        user.setIdCard(param.getIdCard());
        user.setIsIdentity(1);

        int i = userMapper.updateById(user);
        if (i<=0){
            throw new ValidatorException("实名认证失败");
        }
    }


    public void idCardUnique(String idCard) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("id_card", idCard);
        User user = userMapper.selectOne(queryWrapper);
        if (null != user) {
            throw new ValidatorException("身份证已经存在");
        }
    }


    @Override
    public Boolean isIdentity(Long id){
        User user = userMapper.selectById(id);
        if (null != user && null != user.getIsIdentity()) {
            if (user.getIsIdentity().equals(Integer.valueOf(1))){
                return true;
            }
            return false;
        }
        return false;
    }

    @Override
    public Map<Long, User> queryByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return new HashMap<>();
        }
        List<User> users = userMapper.selectBatchIds(ids);
        Map<Long, User> result = new HashMap<>();
        for (User user : users) {
            result.put(user.getId(), user);
        }
        return result;
    }

    @Override
    public void updateUserInfoOfRole(UserParam param) {
        ValidatorUtil.require(param.getId(), "用户id");
        ValidatorUtil.require(param.getRole(), "角色id");

        User user = userMapper.selectById(param.getId());

        if (null == user){
            throw new ValidatorException("用户不存在");
        }

        UserRole userRole = userRoleMapper.selectById(Long.valueOf(param.getRole()));
        if (null == user){
            throw new ValidatorException("角色不存在");
        }

        if (!param.getRole().equals(user.getRole())){
            user.setRole(param.getRole());
            userMapper.updateById(user);

            // 强制退出
            if (redisUtil.existKey(TokenUtils.getAdminRedisKey(user.getUsername(), user.getPassword()))) {
                String oldToken = redisUtil.getValue(TokenUtils.getAdminRedisKey(user.getUsername(), user.getPassword()));
                redisUtil.delKey(oldToken);
            }
        }
    }

    @Override
    public void modifyUserStatus(UserParam param) {
        ValidatorUtil.require(param.getId(), "用户id");
        ValidatorUtil.require(param.getStatus(), "用户状态");

        User user = userMapper.selectById(param.getId());

        if (null == user){
            throw new ValidatorException("用户不存在");
        }

        if (!param.getStatus().equals(user.getStatus())){
            user.setStatus(param.getStatus());
            userMapper.updateById(user);

            // 强制退出
            if (redisUtil.existKey(TokenUtils.getAdminRedisKey(user.getUsername(), user.getPassword()))) {
                String oldToken = redisUtil.getValue(TokenUtils.getAdminRedisKey(user.getUsername(), user.getPassword()));
                redisUtil.delKey(oldToken);
            }
        }
    }

}




